/**
 * Created by wangshhj on 2018/1/16.
 */
import React, { Component } from "react";
import { base, viewModel} from 'nc-lightapp-front';
let { setGlobalStorage, getGlobalStorage, removeGlobalStorage } = viewModel;

const { NCTable, NCButton, NCFormControl, NCNumber, NCCheckbox , NCCol} = base;
const Button = NCButton;
const Checkbox = NCCheckbox;
const Col = NCCol;
const Table = NCTable;

let bodyKey = null; //当前行的key
let currentRowIndex = null; //当前行的index

const defaultProps = {  //复选框
    prefixCls: "bee-table",
    multiSelect: {
        type: "checkbox",
        param: "key"
    }
};


//创建转单
export function createTransferTable({
    headTableId,
    bodyTableId,
    fullTableId,
    setTableBodyData,
    setTransferListValue,
    comType = 'hasCheckBox_child',
    needIndex = true,
    transferBtnText = '转单',
    onTransferBtnClick,
    containerSelector,
    onChangeViewClick,
    showSeletedArea = true,//全部多来源转单不显示已选列表
    showSeletedBtn = true, //普通多来源转单不显示查看已选按钮
    tableType = 'nest', //表格显示类型 nest:主子表 full:主子拉平
    selectArea, //已选列表底部栏自定义区域
    onCheckedChange,//勾选回调函数
    onClearAll, //已选列表清空回调函数
    onSelectedItemRemove,
    cacheItem, //需要缓存的字段
    editableItem, //可编辑的字段
    afterEvent, //可编辑字段的编辑后事件

}) {
    if (!this.state.transferTable.hasOwnProperty(headTableId)) {
        this.state.transferTable[headTableId] = {
            [headTableId]: {
                tableType: tableType,
                bodyData: {},
                outerData: [],
                showFullTable: tableType === 'full',
                firstTime: true,
                bodyTableId: bodyTableId
            },
            selected: {
                selectedShow: false,
                masterAmount: 0, //主表已选数量
                bodyAmount: 0, //子表已选数量
                masterCheckedId: [], //存放已选主表id，用于复选框半选
                selectedData: {
                    selAll: false,
                    masterSelData: {},
                    childSelData: {}
                }
            },
            transformForm: {//转单列表
                activeIndex: 0,
                show: false, //是否显示转单视图
                listData: {} //转单列表数据
            }
        }
    }

    if (!this.state.meta) {
        return false;
    }

    let transferTable = this.state.transferTable[headTableId];
    //外层表格数据
    let currentTable = this.state.transferTable[headTableId][headTableId];

    if (currentTable.showFullTable) {
        if (!this.state.meta[fullTableId]) {
            return false;
        }
        //headTableId = fullTableId;
    } else if (!this.state.meta.hasOwnProperty(headTableId) || !this.state.meta[headTableId]) {
        return false;
    }

    // if (!this.state.transferTable[headTableId][headTableId]) {
    //     return false;
    // }


    let data = currentTable.outerData;
    let transformForm = this.state.transferTable[headTableId].transformForm;

    this.setTableBodyData = setTableBodyData;//设置内嵌表格数据
    this.setTransferListValue = setTransferListValue;//设置转单列表数据
    this.onTransferBtnClick = onTransferBtnClick;//转单按钮回调函数
    this.onChangeViewClick = onChangeViewClick;//切换视图回调函数
    this.onCheckedChange = onCheckedChange;//复选框勾选回调函数
    this.onClearAll = onClearAll;//已选列表清空回调函数

    //表格的列模板信息
    let columns = this.state.meta[headTableId] && this.state.meta[headTableId].items;//主表模板
    let bodyColumn = bodyTableId && this.state.meta[bodyTableId] ? this.state.meta[bodyTableId].items : [];//子表模板
    let fullColumns = fullTableId && this.state.meta[fullTableId] ? this.state.meta[fullTableId].items : [];//主子拉平模板
    //外层容器宽度
    let containerWidth = document.querySelector(containerSelector) && document.querySelector(containerSelector).clientWidth;

    //===========================子表添加复选框===========================================
    //子表复选框单个勾选
    const onCheckboxChangeChild = (text, record, index, parents, parentsIndex) => {

        let selectedData = transferTable.selected.selectedData;
        let master = selectedData.childSelData[parents.key];
        let flag = true;
        if (!master) {
            selectedData.childSelData[parents.key] = {
                [record.key]: {
                    sel: true,
                    data: record,
                    // masterData: parents
                }
            }
            selectedData.masterSelData[parents.key] = {
                sel: true,
                data: parents
            }

            setAllSelVal('body', true, parents.key, record.key);//多来源有全部页签需要单独统计已选数据
            //判断主表是否全选
            if (isMasterCheckAll()) {
                selectedData.selAll = true;
            }
        } else {
            let child = master[record.key];
            flag = !child;
            if (!child) {
                selectedData.childSelData[parents.key][record.key] = {
                    sel: true,
                    data: record,
                    // masterData: parents
                }

                selectedData.masterSelData[parents.key] = {
                    sel: true,
                    data: parents
                }
                setAllSelVal('body', true, parents.key, record.key);//多来源有全部页签需要单独统计已选数据
                //判断子表数据是否全选
                if (isChildCheckAll(parents)) {
                    setMasterId(parents.key, true);
                }
                //判断主表是否全选
                if (isMasterCheckAll()) {
                    selectedData.selAll = true;
                }
            } else {
                delete selectedData.childSelData[parents.key][record.key];
                let childAll = selectedData.childSelData[parents.key];
                if (Object.keys(childAll).length === 0) {
                    delete selectedData.childSelData[parents.key];
                    delete selectedData.masterSelData[parents.key];
                }
                setAllSelVal('body', false, parents.key, record.key);//多来源有全部页签需要单独统计已选数据
                selectedData.selAll = false;
                setMasterId(parents.key, false);
            }
        }
        this.state.transferTable[headTableId] = transferTable;
        this.setState({
            transferTable: this.state.transferTable
        },
            () => {
                onCheckedChange && onCheckedChange(flag, record, index, null, parentsIndex)
            });

    };


    //多来源有全部页签需要单独统计已选数据
    //type:head/body 勾选的类型 status:选中状态 headId:主表id bodyId:子表id
    const setAllSelVal = (type, status, headId, bodyId) => {
        let allSelected = this.state.transferTable.allSelected;
        if (allSelected) {
            if (status) {
                if (!allSelected.selIds[headId]) {
                    if (type === 'head') {//主表勾选
                        allSelected.selIds[headId] = [];
                    } else {//子表勾选
                        allSelected.selIds[headId] = [bodyId];
                    }
                } else if (bodyId && !allSelected.selIds[headId].includes(bodyId)) {//子表勾选
                    allSelected.selIds[headId].push(bodyId);
                }
            } else {
                if (type === 'head') { //主表取消勾选
                    delete allSelected.selIds[headId];
                } else { //子表取消勾选
                    allSelected.selIds[headId].splice(allSelected.selIds[headId].indexOf(bodyId), 1);
                    if (allSelected.selIds[headId].length === 0) {
                        delete allSelected.selIds[headId];
                    }
                }
            }
        }
    }
    //子表添加复选框列
    const renderColumnsMultiSelectChild = (columns, records, indexs, comType) => {
        let { multiSelect } = defaultProps;
        let indexCol = [
            {
                label: '序号',
                attrcode: "indexCol",
                itemtype: 'customer',
                dataIndex: "indexCol",
                visible: true,
                width: 80,
                render: (text, record2, index) => {
                    return (
                        <span>
                            {index + 1}
                        </span>
                    )
                }
            }
        ]; // 添加序号列
        let newColumn = columns;
        if (needIndex) {
            newColumn = indexCol.concat(newColumn);
        }

        //  根据组件类型，判断是否带复选框
        if (comType == 'hasCheckBox_child') {
            if (multiSelect && multiSelect.type === "checkbox") {
                let parId = transferTable.selected.selectedData.childSelData[records.key];
                let defaultColumns = [
                    {
                        label: '',
                        attrcode: "checkbox",
                        itemtype: 'customer',
                        dataIndex: "checkbox",
                        width: 50,
                        visible: true,
                        render: (text, record, index) => {
                            return (
                                <Checkbox
                                    onBlur={() => {}}
                                    className="table-checkbox"
                                    checked={(parId && parId[record.key]) ? true : false}
                                    onChange={onCheckboxChangeChild.bind(this, text, record, index, records, indexs)}
                                />
                            );
                        }
                    }
                ];
                newColumn = defaultColumns.concat(newColumn);
            }
        } else if (comType == 'selectedList') { //已选列表增加操作列
            let oprColumn = {
                label: '操作',
                attrcode: "operate",
                itemtype: 'customer',
                dataIndex: "operate",
                width: 50,
                //fixed: "right",
                visible: true,
                render: (text, record, index) => {
                    return (
                        <a href="javascript:;" onClick={() => {
                            //移除子表
                            onSelectedItemRemove && onSelectedItemRemove(record);
                            onCheckboxChangeChild(text, record, index, records, index);
                        }}>移除</a>
                    );
                }
            }
            newColumn = [...newColumn, oprColumn];
        }

        return newColumn;
    };

    //判断子表是否全选
    const isChildCheckAll = (parents) => {
        let innerDataLen = currentTable.bodyData.data[parents.key].rows.length;
        let childSelLen = Object.keys(transferTable.selected.selectedData.childSelData[parents.key]).length;
        if (innerDataLen === childSelLen) {
            return true;
        }
        return false;
    }

    //判断主表是否全选
    const isMasterCheckAll = () => {
        let outerDataLen = currentTable.outerData.length;
        let masterSelLen = transferTable.selected.masterCheckedId.length;
        if (outerDataLen === masterSelLen) {
            return true;
        }
        return false;
    }

    //判断主表或子表是否有选中项
    const isHaveCheck = () => {
        let masterCheckFlag = false;
        let childCheckFlag = false;
        let masterChecklen = Object.keys(transferTable.selected.selectedData.masterSelData).length;
        let datalen = currentTable.outerData.length;
        if (masterChecklen > 0 && masterChecklen < datalen) {
            masterCheckFlag = true;//主表有选中项,且非全选
        }
        let childChecklen = Object.keys(transferTable.selected.selectedData.childSelData).length;
        if (childChecklen > 0) {
            childCheckFlag = true;
        }
        if (masterCheckFlag || childCheckFlag) {
            return true;
        }
        return false;
    }


    //将当前页所有数据加入/取消已选择
    const selectAllMaster = (flag) => {
        let { outerData } = currentTable;
        let innerData = currentTable.bodyData;
        outerData.map((item, index) => {
            switchMasterChecked(flag, item.values, item.values, index);
        });
    }

    //============================================主表添加复选框==================================
    //主表复选框全选点击事件
    const onAllCheckChange = (selAll) => {
        transferTable.selected.selectedData.selAll = selAll;
        selectAllMaster(selAll);
        this.state.transferTable[headTableId] = transferTable;
        this.setState({
            transferTable: this.state.transferTable
        });
    };

    //主表复选框单个勾选
    const onCheckboxChange = (text, record, index) => {
        let curKey = record.headKey || record.key;//主子拉平取主表id
        switchMasterChecked(!transferTable.selected.selectedData.masterSelData[curKey], text, record, index);
    };

    //主表切换勾选状态 flag:开关状态，默认选中
    const switchMasterChecked = (flag = true, text, record, index) => {
        let selectedData = transferTable.selected.selectedData;
        let bodyData = currentTable.bodyData.data;
        let curKey = record.headKey || record.key;//主子拉平取主表id
        let delBodyData;
        //选中
        if (flag) {
            selectedData.masterSelData[curKey] = {
                sel: true,
                data: record
            }
            setAllSelVal('head', true, curKey);//多来源有全部页签需要单独统计已选数据
            let innerData = bodyData[curKey];
            // getData(true, record, index);//选中主表时加载子表数据
            innerData = bodyData[curKey];
            if (innerData) {
                selectedData.childSelData[curKey] = {};
                innerData.rows.map((item, index) => {
                    selectedData.childSelData[curKey][item.values.key] = {
                        sel: true,
                        data: item
                    }
                    setAllSelVal('body', true, curKey, item.values.key);
                })
            }
            setMasterId(curKey, true);//选择主表时记录主表id
            //判断主表是否全选
            if (isMasterCheckAll()) {
                selectedData.selAll = true;
            }
        } else { //移除 
            selectedData.selAll = false;
            setMasterId(curKey, false);
            setAllSelVal('head', false, curKey);//多来源有全部页签需要单独统计已选数据
            if (selectedData.masterSelData[curKey]) {
                delete selectedData.masterSelData[curKey]
            }
            if (selectedData.childSelData[curKey]) {
                delBodyData = selectedData.childSelData[curKey]; //记录被删除的子表数据
                delete selectedData.childSelData[curKey];
            }
        }
        this.state.transferTable[headTableId] = transferTable;
        this.setState({
            transferTable: this.state.transferTable
        },
            () => {
                let bdata = flag ? selectedData.childSelData[curKey] : delBodyData;
                let bodySelData = bdata ? Object.values(bdata).map(item => item.data.values || item.data) : [];//勾选主表获取子表数据
                onCheckedChange && onCheckedChange(flag, record, index, bodySelData);
            });
    }
    //主表添加复选框列
    const renderColumnsMultiSelect = (columns) => {
        //const { data, checkedArray } = currentTable.mainCheckObj;
        const { multiSelect } = defaultProps;
        let indexCol = [
            {
                label: '序号',
                attrcode: "indexCol",
                itemtype: 'customer',
                dataIndex: "indexCol",
                visible: true,
                width: 80,
                render: (text, record, index) => {
                    return (
                        <span>
                            {index + 1}
                        </span>
                    )
                }
            }
        ]; // 添加序号列
        let newColumn = columns;
        if (needIndex) {
            newColumn = indexCol.concat(newColumn);
        }

        if (multiSelect && multiSelect.type === "checkbox") {
            let selAll = transferTable.selected.selectedData.selAll;
            //主表或子表是否有选中项
            let indeterminate = isHaveCheck();
            let defaultColumns = [
                {
                    label: (
                        <Checkbox
                            onBlur={() => {}}
                            className="table-checkbox"
                            checked={selAll}
                            indeterminate={indeterminate && !selAll}
                            onChange={onAllCheckChange.bind(this, !transferTable.selected.selectedData.selAll)}
                        />
                    ),
                    attrcode: "checkbox",
                    itemtype: 'customer',
                    dataIndex: "checkbox",
                    visible: true,
                    width: 50,
                    render: (text, record, index) => {
                        let parentId = transferTable.selected.masterCheckedId.includes(record.key);
                        let fullChekced = transferTable.selected.selectedData.childSelData[record.headKey] && transferTable.selected.selectedData.childSelData[record.headKey][record.key];
                        let indeterminate_bool = transferTable.selected.selectedData.childSelData[record.key];//有子元素选中
                        return (
                            <Checkbox
                                onBlur={() => {}}
                                className="table-checkbox"
                                checked={!currentTable.showFullTable ? parentId : fullChekced}
                                indeterminate={indeterminate_bool && !parentId}
                                onChange={!currentTable.showFullTable ? onCheckboxChange.bind(this, text, record, index) : onCheckboxChangeFull.bind(this, text, record, index)}
                            />
                        );
                    }
                }
            ];
            newColumn = defaultColumns.concat(newColumn);
        }

        return newColumn;
    };


    //主子拉平切换勾选状态
    const onCheckboxChangeFull = (text, record, index) => {
        let selectedData = transferTable.selected.selectedData;
        let master = selectedData.childSelData[record.headKey];
        let allSelected = this.state.transferTable.allSelected && this.state.transferTable.allSelected.selectedData;
        let flag = true;
        if (!master) {
            selectedData.childSelData[record.headKey] = {
                [record.key]: {
                    sel: true,
                    data: record
                }
            }
            selectedData.masterSelData[record.headKey] = {
                sel: true,
                data: record
            }
            //记录全部多来源主子拉平的勾选数据
            if (allSelected) {
                allSelected.childSelData[record.headKey] = {
                    [record.key]: {
                        sel: true,
                        data: record
                    }
                }
                allSelected.masterSelData[record.headKey] = {
                    sel: true,
                    data: record
                }
            }
            setAllSelVal('body', true, record.headKey, record.key);
            setMasterId(record.headKey, true);
            //判断主表是否全选
            if (isMasterCheckAll()) {
                selectedData.selAll = true;
                if (allSelected) {
                    allSelected.selAll = true;
                }
            }
        } else {
            let child = master[record.key];
            flag = !child;
            if (!child) {
                selectedData.childSelData[record.headKey][record.key] = {
                    sel: true,
                    data: record
                }

                selectedData.masterSelData[record.headKey] = {
                    sel: true,
                    data: record
                }
                //记录全部多来源主子拉平的勾选数据
                if (allSelected) {
                    allSelected.childSelData[record.headKey][record.key] = {
                        sel: true,
                        data: record
                    }

                    allSelected.masterSelData[record.headKey] = {
                        sel: true,
                        data: record
                    }
                }
                setAllSelVal('body', true, record.headKey, record.key);
                //判断主表是否全选
                if (isMasterCheckAll()) {
                    selectedData.selAll = true;
                    if (allSelected) {
                        allSelected.selAll = true;
                    }
                }
            } else {
                delete selectedData.childSelData[record.headKey][record.key];
                let childAll = selectedData.childSelData[record.headKey];
                if (Object.keys(childAll).length === 0) {
                    delete selectedData.childSelData[record.headKey];
                    delete selectedData.masterSelData[record.headKey];
                }
                selectedData.selAll = false;
                //删除全部多来源主子拉平的勾选数据
                if (allSelected) {
                    delete allSelected.childSelData[record.headKey][record.key];
                    let childAll = allSelected.childSelData[record.headKey];
                    if (Object.keys(childAll).length === 0) {
                        delete allSelected.childSelData[record.headKey];
                        delete allSelected.masterSelData[record.headKey];
                    }
                    allSelected.selAll = false;
                }
                setMasterId(record.headKey, false);
                setAllSelVal('body', false, record.headKey, record.key);
            }
        }
        this.state.transferTable[headTableId] = transferTable;
        this.setState({
            transferTable: this.state.transferTable
        },
            () => {
                onCheckedChange && onCheckedChange(flag, record, index)
            });
    };

    //已选列表主子拉平移除
    const clearSelectedFullData = (text, record, index) => {
        let selectedData = transferTable.selected.selectedData;
        delete selectedData.childSelData[record.headKey][record.key];
        let childAll = selectedData.childSelData[record.headKey];
        if (Object.keys(childAll).length === 0) {
            delete selectedData.childSelData[record.headKey];
            delete selectedData.masterSelData[record.headKey];
        }
        setAllSelVal('body', false, record.headKey, record.key);//多来源有全部页签需要单独统计已选数据
        selectedData.selAll = false;
        setMasterId(record.headKey, false);
        this.state.transferTable[headTableId] = transferTable;
        this.setState({
            transferTable: this.state.transferTable
        });
    }

    //已选列表清空事件
    const handleClearAllSelected = () => {
        transferTable.selected.masterCheckedId = [];//清空已选主表id
        transferTable.selected.selectedData.selAll = false;//取消全选
        transferTable.selected.selectedData.masterSelData = {};
        transferTable.selected.selectedData.childSelData = {};
        transferTable.selected.masterAmount = 0;
        transferTable.selected.bodyAmount = 0;
        this.setState({
            transferTable: this.state.transferTable
        }, () => {
            onClearAll && onClearAll();
        });
    }

    if (data && currentTable.firstTime) {
        currentTable.firstTime = false;
        //初始化内嵌表格数据
        // currentTable.bodyData = {
        //     column: {},
        //     data: {}
        // };
        // currentTable.childCheckObj = {};

        // //初始化复选框
        // currentTable.mainCheckObj = {
        //     checkedAll: false,
        //     checkedArray: [],
        //     data: data
        // };
        //设置每行是否勾选
        // data.map((val, index) => {
        //     currentTable.mainCheckObj.checkedArray.push(false)
        // });
    }

    //  根据组件类型，判断是否带复选框
    let column = columns;
    let classByType = null;
    if (comType == 'hasCheckBox' || comType == 'hasCheckBox_child') {
        column = renderColumnsMultiSelect.call(this, columns);
        fullColumns = renderColumnsMultiSelect.call(this, fullColumns);
        classByType = 'hasCheckBox'
    }

    //选择主/子表时记录主表id id:主表id flag:选中/取消选中
    const setMasterId = (id, flag) => {
        let { masterCheckedId, selectedData } = transferTable.selected;
        if (!masterCheckedId.includes(id) && flag) {
            masterCheckedId.push(id);
        } else if (masterCheckedId.indexOf(id) !== -1 && !selectedData.selAll) {
            masterCheckedId.splice(masterCheckedId.indexOf(id), 1);
        }
    }
    const editableJSX = (item, value, index, outerRecordKey) => {
        let editItem = null;
        switch (item.itemtype) {
            case 'number':
                // scale = isWrong(scale) ? (item.scale || 0) : scale;
                editItem = <NCNumber
                    value={value}
                    autoFocus={true}
                    onChange={
                        (valueChange) => {
                            
                            let transferTable = this.state.transferTable;
                            if (outerRecordKey) {
                                transferTable[headTableId][headTableId].bodyData.data[outerRecordKey].rows[index].values[item.attrcode].value = valueChange;
                            } else {
                                transferTable[headTableId][headTableId].outerData[index].values[item.attrcode].value = valueChange;
                            }
                            this.setState({
                                transferTable: transferTable
                            });
                        }
                    } />;
                break;
            default:
                editItem = <span>{value}</span>
                break;
        }
        return editItem;
    }

    // 处理模板
    const createNewCol = (column, outerRecordKey) => {

        let result = [];
        column.map((item) => {
            let render = null;
            if (item.itemtype !== 'customer' && item.visible) {
                render = (text, record, index) => {
                    if (record[item.attrcode]) {
                        let isEdit = record[item.attrcode].isEdit
                        let display = record[item.attrcode].display;
                        let value = record[item.attrcode].value;
                        let dom = '';
                        if (display || display === 0) {
                            dom = display
                        } else {
                            dom = value
                        }
                        return isEdit ?
                            <div
                                onBlur={() => {
                                    let transferTable = this.state.transferTable;
                                    let serverRowRecord = null; //服务端获取的行数据。作为修改前数据使用。
                                    if (outerRecordKey) { //存在外部记录key，说明当前单元格是子单元格
                                        serverRowRecord = this.serverBodyData[headTableId][outerRecordKey].rows[index].values;
                                        transferTable[headTableId][headTableId].bodyData.data[outerRecordKey].rows[index].values[item.attrcode].isEdit = false;
                                    } else {
                                        serverRowRecord = this.serverOuterData[headTableId][index].values;
                                        transferTable[headTableId][headTableId].outerData[index].values[item.attrcode].isEdit = false;
                                    }
                                    this.setState({
                                        transferTable: transferTable
                                    }, () => {
                                        afterEvent(item.attrcode, dom, record, index, serverRowRecord);
                                    });
                                }}
                            >
                                {
                                    editableJSX(item, dom, index, outerRecordKey)
                                }
                            </div>
                            :
                            <span
                                style={{display: 'inline-block', width: '100%', height: '28px', lineHeight: '28px'}}
                                onClick={() => {
                                    ///console.log(666, item.attrcode);
                                    if (!editableItem.includes(item.attrcode)) {
                                        return;
                                    }
                                    let transferTable = this.state.transferTable;
                                    if (outerRecordKey) {
                                        transferTable[headTableId][headTableId].bodyData.data[outerRecordKey].rows[index].values[item.attrcode].isEdit = true;
                                    } else {
                                        transferTable[headTableId][headTableId].outerData[index].values[item.attrcode].isEdit = true;
                                    }
                                    this.setState({
                                        transferTable: transferTable
                                    });
                                }}
                            >
                                {dom}
                            </span>


                    }
                };
            } else {
                render = item.render
            }
            if (item.visible) {
                result.push({ ...item, render, key: item.attrcode, title: item.label })
            }
        });
        return result;
    };


    //  处理数据
    const createNewData = (data) => {
        let datas = [];
        data.map((val, index) => {
            val = val.values || val;
            datas.push(val);
        });
        return datas
    };

    //表格展开显示的内容
    //渲染子表表格数据及复选框
    const expandedRowRender = (record, index, comType) => {
        // if (JSON.stringify(bodyColumn) == "{}") {
        //     return false
        // }
        // if (!currentTable.childCheckObj.hasOwnProperty(record.key)) {
        //     return false
        // }


        let newColumn = bodyColumn;
        let classByType = null;
        let curKey = record.headKey || record.key;

        newColumn = renderColumnsMultiSelectChild.call(this, newColumn, record, index, comType);

        if (JSON.stringify(currentTable.bodyData) !== "{}" && currentTable.bodyData.data.hasOwnProperty(curKey)) {
            let data = null;
            //已选列表的子表移除时需要删除行数据
            if (comType === 'selectedList') {
                data = createNewData(Object.values(transferTable.selected.selectedData.childSelData[curKey] || {}).map(item => item.data));
            } else {
                data = createNewData(currentTable.bodyData.data[record.key].rows);
            }
            return (
                <Col md={12} xs={12} sm={12}>
                    <Table
                        columns={createNewCol(newColumn, record.key)}
                        data={data}
                        scroll={{ x: true, y: 450 }}
                    />

                </Col>
            );
        }
    };

    //当点击展开的时候才去请求内嵌表格数据
    const getData = (expanded, record, index) => {
        let selectedData = transferTable.selected;
        if (expanded) {
            // transferTable.selected.expandKey = [record.key];
            bodyKey = record.key;
            currentRowIndex = record.rowIndex;
            //判断是否已经有该子表数据，如果有，不需要再次请求。
            //let hasThisChild = currentTable.childCheckObj.hasOwnProperty(bodyKey);
            this.transferTable.setChildTransferTableData(headTableId, record, currentTable.bodyData.data[record.key], currentTable.childId);
        }
    };

    //查看已选列表
    const viewSelectedList = () => {
        let selectedData = transferTable.selected.selectedData;
        if (JSON.stringify(selectedData.masterSelData) === '{}' && JSON.stringify(selectedData.childSelData) === '{}') {
            return false;
        } else {
            transferTable.selected.selectedShow = !transferTable.selected.selectedShow;//已选列表弹窗显示状态
            this.state.transferTable[headTableId] = transferTable;
            this.setState({
                transferTable: this.state.transferTable
            });
        }
    }

    //关闭已选列表
    const closeSelectedList = () => {
        transferTable.selected.selectedShow = false;
        this.state.transferTable[headTableId] = transferTable;
        this.setState({
            transferTable: this.state.transferTable
        });
    }

    //设置已选列表columns
    const setSelectedColumns = (columns) => {
        let result = [];
        let operateColumn = {
            title: '操作',
            attrcode: "operate",
            itemtype: 'customer',
            dataIndex: "operate",
            width: "50px",
            //fixed: "right",
            visible: true,
            render: (text, record, index) => {
                return (
                    <a href="javascript:;" onClick={() => {
                        //移除主表
                        let selData = this.state.transferTable[headTableId].selected.selectedData;
                        let childSelData = selData.childSelData[record.key]
                        let bodys = [];
                        for (let headKey in childSelData) {
                            bodys.push(childSelData[headKey].data);
                        }
                        onSelectedItemRemove && onSelectedItemRemove(record, bodys);
                        !currentTable.showFullTable ?
                            onCheckboxChange(text, record, index) :
                            clearSelectedFullData(text, record, index)
                    }}>移除</a>
                );
            }
        }
        columns && columns.map(item => {
            if (item.attrcode !== 'checkbox' && item.label !== '操作') {
                result.push(item);
            }
        });
        return [...result, operateColumn];
    }

    //统计已选列表数量
    const getSelectedAmount = () => {
        let allSelected = this.state.transferTable.allSelected;//多来源转单全部页签
        let bodyArr = [];
        //统计子表选中数量
        Object.values(transferTable.selected.selectedData.childSelData).forEach(item => {
            Object.keys(item).forEach(key => {
                bodyArr.push(key);
            });
        });
        //统计子表选中数量
        let masterAmount = Object.keys(transferTable.selected.selectedData.masterSelData).length;//主表选中数量
        let bodyAmount = bodyArr.length;//子表选中数量
        //多来源有全部时统计全部页签的勾选重量
        if (allSelected) {
            let bodys = 0;
            Object.values(allSelected.selIds).forEach(item => {
                bodys += item.length;
            });
            masterAmount = Object.keys(allSelected.selIds).length;
            bodyAmount = bodys;
            allSelected.masterAmount = masterAmount;
            allSelected.bodyAmount = bodyAmount;
        } else { //单来源统计数量
            transferTable.selected.masterAmount = masterAmount;
            transferTable.selected.bodyAmount = bodyAmount;
        }
        return { masterAmount, bodyAmount };
    }

    //获取已选列表主表数据
    const getMasterData = (data) => {
        return Object.values(data.masterSelData).map(item => item.data);
    }

    //获取已选列表主子拉平数据
    const getSelectedFullData = (data) => {
        let { masterSelData, childSelData } = data;
        let result = [];
        for (let key in childSelData) {
            Object.values(childSelData[key]).forEach(item => {
                let childVal = item.data.values || item.data;
                let newData = Object.assign(JSON.parse(JSON.stringify(masterSelData[key].data)), JSON.parse(JSON.stringify(childVal)));//合并后的主子拉平数据
                newData.headKey = key;
                result.push(newData);
            });
        }
        return result;
    }

    //点击生成按钮
    const handleGenerateClick = () => {
        let selIds = [];
        //获取已选列表主子表id
        let masterData = transferTable.selected.selectedData.masterSelData;
        for (let key in masterData) {
            let childData = transferTable.selected.selectedData.childSelData[key];
            let bodys = [];
            for (let id in childData) {
                let values = childData[id].data.values || childData[id].data;
                let itemsJson = {};
                cacheItem.forEach((item) => {
                    let itemValue = values[item];
                    itemValue && (itemsJson[item] = itemValue);
                })
                bodys.push({
                    pk: id,
                    ts: values.ts && values.ts.value,
                    ...itemsJson
                })
            }
            let values = masterData[key].data;
            let itemsJson = {};
            cacheItem.forEach((item) => {
                let itemValue = values[item];
                itemValue && (itemsJson[item] = itemValue);
            })
            selIds.push({
                head: {
                    pk: key,
                    ts: values.ts && values.ts.value,
                    ...itemsJson
                },
                bodys: bodys
            });
        }
        transferTable.selected.selectedShow = false;//隐藏已选列表
        // transferTable.transformForm.show = true;//显示转单列表
        transferTable.transformForm.activeIndex = 0;//默认选中第一条转单
        transferTable.transformForm.list = [];
        setGlobalStorage('sessionStorage', 'transferIds', JSON.stringify(selIds));//将主子表id缓存起来

        this.state.transferTable[headTableId] = transferTable;
        this.setState({
            transferTable: this.state.transferTable
        },
            () => {
                if (typeof onTransferBtnClick === 'function') {
                    onTransferBtnClick(selIds);
                }
            }
        );
    }

    //点击切换视图
    const handleChangeView = () => {
        if (typeof onChangeViewClick === 'function') {
            onChangeViewClick();
        }
    }

    //将主子表数据拼成主子拉平数据
    const createFullData = (data) => {
        let { outerData, bodyData } = data;
        let result = [];
        let headData = {};
        outerData.map(item => {
            headData[item.rowId] = item.values;
        });
        for (let key in bodyData.data) {
            bodyData.data[key].rows.map(item => {
                let newData = Object.assign(JSON.parse(JSON.stringify(headData[key])), JSON.parse(JSON.stringify(item.values)));//合并后的主子拉平数据
                newData.headKey = key;
                result.push(newData);
            });
        }
        return result;
    }

    let selectedAmount = getSelectedAmount();//已选数据数量
    // //==================转单部分========================

    return (
        <div className="transfertable-main">
            <div className={["insertTable", classByType].join(' ')}>
                {
                    (!transferTable.selected.selectedShow && !transformForm.show) ? //待选列表
                        (!currentTable.showFullTable ?
                            (tableType === 'simple' ? //单表
                                <NCTable
                                    columns={createNewCol(column)}
                                    data={createNewData(currentTable.outerData)}
                                    scroll={{ x: true }}
                                /> :
                                // (tableType === 'nest' ? //显示主子表
                                //     <NCTable
                                //         columns={createNewCol(column)}
                                //         data={createNewData(currentTable.outerData)}
                                //         //onExpand={getData.bind(this)}
                                //         expandedRowRender={(record, index) => expandedRowRender(record, index, comType)}
                                //         // expandedRowKeys={transferTable.selected.expandKey}
                                //         // autoExpandParent={false}
                                //         scroll={{ x: true }}
                                //     /> :
                                //     <NCTable
                                //         columns={createNewCol(column)}
                                //         data={createNewData(currentTable.outerData)}
                                //         //onExpand={getData.bind(this)}
                                //         expandedRowRender={(record, index) => expandedRowRender(record, index, comType)}
                                //         // expandedRowKeys={transferTable.selected.expandKey}
                                //         // autoExpandParent={false}
                                //         scroll={{ x: true }}
                                //     />
                                // )
                                (
                                    <NCTable
                                        columns={createNewCol(column)}
                                        data={createNewData(currentTable.outerData)}
                                        expandedRowRender={(record, index) => expandedRowRender(record, index, comType)}
                                        scroll={{ x: true }}
                                    />
                                )
                            )
                            :
                            //显示主子拉平
                            <NCTable
                                columns={createNewCol(fullColumns)}
                                data={createFullData(currentTable)}
                                scroll={{ x: true }}
                            />
                        )
                        :
                        (transferTable.selected.selectedShow ?
                            // 已选列表
                            <div className="selected-list">
                                <div className="header-area">
                                    <span className="header-title">已选列表</span>
                                    <div className="header-right">
                                        <span className="item" onClick={handleClearAllSelected.bind(this)}>清空</span>
                                        {tableType !== 'simple' ? <a href="javascript:;" onClick={handleChangeView.bind(this)}>切换</a> : ''}
                                        <span className="hide iconfont icon-mianbaoxie" onClick={closeSelectedList.bind(this)}></span>
                                    </div>
                                </div>
                                <div className="content-area">
                                    {
                                        !currentTable.showFullTable ? //显示主子表
                                            tableType === 'simple' ? //单表
                                                <NCTable
                                                    className="insertTable"
                                                    columns={setSelectedColumns(createNewCol(column))}
                                                    data={getMasterData(transferTable.selected.selectedData)}
                                                    rowKey={(record) => record.key}
                                                    scroll={{ x: true }}
                                                /> :
                                                tableType === 'nest' ? //显示主子表
                                                    <NCTable
                                                        className="insertTable"
                                                        columns={setSelectedColumns(createNewCol(column))}
                                                        data={getMasterData(transferTable.selected.selectedData)}
                                                        //onExpand={getData.bind(this)}
                                                        expandedRowRender={(record, index) => expandedRowRender(record, index, "selectedList")}
                                                        rowKey={(record) => record.key}
                                                        scroll={{ x: true }}
                                                    /> : ''
                                            :
                                            //主子拉平
                                            <NCTable
                                                columns={setSelectedColumns(createNewCol(fullColumns))}
                                                data={getSelectedFullData(transferTable.selected.selectedData)}
                                                scroll={{ x: true }}
                                            />
                                    }
                                </div>
                            </div>
                            : '')
                }

            </div>
            {
                !transformForm.show && showSeletedArea ?
                    <div className="fixed-bottom-outer" style={{ width: containerWidth }}>
                        <div className="fixed-bottom-container bottom-area-container">
                            {
                                //普通多来源不显示查看已选按钮
                                showSeletedBtn ?
                                    <div className="area-left">
                                        {
                                            transferTable.selected.selectedShow ?
                                                <Button className="middle-btn" onClick={closeSelectedList.bind(this)}>全部列表</Button>
                                                :
                                                <Button
                                                    className="middle-btn"
                                                    onClick={viewSelectedList.bind(this)}
                                                    disabled={JSON.stringify(transferTable.selected.selectedData.masterSelData) === '{}'}
                                                >
                                                    查看已选
                                                </Button>
                                        }
                                    </div> : ''
                            }
                            <div className="area-center">
                                <span>合计：{selectedAmount.masterAmount}条
                                {tableType !== 'simple' ? <span style={{ marginLeft: 26 }}>共{selectedAmount.bodyAmount}行</span> : ''}
                                </span>
                            </div>
                            {
                                selectArea ?
                                    <div className="area-custom">
                                        {selectArea && typeof selectArea == 'function' && selectArea()}
                                    </div> : ''
                            }
                            <div className="area-right">
                                <Button
                                    className="main-button button-component large-btn"
                                    onClick={handleGenerateClick.bind(this)}
                                    disabled={JSON.stringify(transferTable.selected.selectedData.masterSelData) === '{}'}
                                >{transferBtnText}</Button>
                            </div>
                        </div>
                    </div>
                    : ''
            }
        </div>
    );
}

//创建卡片型转单列表
export function createTransferList({
    headcode,
    transferListId,
    onTransferItemClick,
    onTransferItemSelected
}) {
    if (!this.state.transferList.hasOwnProperty(transferListId)) {
        this.state.transferList[transferListId] = {
            // selected: {
            //     selectedShow: false,
            //     masterAmount: 0, //主表已选数量
            //     bodyAmount: 0, //子表已选数量
            //     masterCheckedId: [], //存放已选主表id，用于复选框半选
            //     selectedData: {
            //         selAll: false,
            //         masterSelData: {},
            //         childSelData: {}
            //     }
            // },
            transformForm: {//转单列表
                activeIndex: 0,
                show: true, //是否显示转单视图
                listData: {}, //转单列表数据
                list: [],
                first: 0 //记录页面第几次进入的
            }
        }
    }
    if (!this.state.meta) {
        return false
    }
    if (!this.state.meta[transferListId] || !this.state.transferList[transferListId]) {
        return false
    }
    let { transferList } = this.state;
    let transformForm = transferList[transferListId].transformForm;


    //转单模板信息
    let transformListMeta = this.state.meta[transferListId].items;
    let dataAreaCode = headcode;

    this.onTransferItemClick = onTransferItemClick;
    this.onTransferItemSelected = onTransferItemSelected;
    //默认选中第一条转单
    if (transformForm.first === 0) {
        transformForm.first++;
    } else if (transformForm.first === 1) {
        transformForm.list[0] &&
            onTransferItemSelected(transformForm.list[0].data, transformForm.list[0].complete, transformForm.activeIndex);
        transformForm.first++;
    }

    console.log('transferList', this.state.transferList)
    //==================转单部分========================

    //转单render
    const transformListRender = () => {
        return transformForm.list && transformForm.list.map((item, index) => {
            return (
                <li className={`${index === transformForm.activeIndex ? "item active" : "item"} ${item.complete && 'complete'}`}
                    onClick={handleTransformListClick.bind(this, item.data, index)}>
                    <span className="index">{index + 1}</span>
                    <span className={`status${item.complete ? ' complete' : ''}`}></span>
                    <div className="content">
                        {
                            transformListMeta.map((val, index) => {
                                let itemVal = item.data.head[dataAreaCode].rows[0].values[val.attrcode];
                                return (
                                    val.visible && <div className="item-inner">
                                        {`${val.label}：`}
                                        <span style={{ paddingLeft: 8 }}>
                                            {`${itemVal &&
                                                (itemVal.display || itemVal.value || '')}`}
                                        </span>
                                    </div>
                                )
                            })

                        }
                    </div>
                </li>
            )
        })
    }
    //点击缩略显示区
    const handleTransformListClick = (v, index) => {
        transformForm.activeIndex = index;
        this.setState({
            transformForm
        }, () => {
            if (typeof onTransferItemClick === 'function') {
                onTransferItemClick(v, index, transformForm.list[index].complete);
            }
        }
        );
    }
    //console.log('transferList', this.state.transferList)
    let flag = transformForm.show && transformForm.list && transformForm.list.length !== 1;
    return (
        <div className={`transfertable-main ${flag && 'show-tranferList'} `}>
            {
                flag ?
                    <div className="transformtable-main">
                        <div className="transform-list">
                            <ul>
                                {transformListRender()}
                            </ul>
                            {!!transformForm.list[0] ? <div className="total-area">共计：<span className="active">{transformForm.list.length}条</span></div> : ''}
                        </div>
                    </div> : ''
            }
        </div>
    )
}
